package com.framework.utils.pay.yunzhanghujiesuan;

import com.alibaba.fastjson.JSONObject;
import com.framework.exception.RRException;
import com.framework.utils.pay.yunzhanghujiesuan.bean.YunjiesuanReportBean;
import com.framework.utils.string.StringUtil;
import com.google.gson.Gson;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static com.framework.utils.HmacSha256.sha256HMAC;

/**
 * 云账户结算上报
 */
public class YunJieSuanReport {

    //商户代码
    private static final String dealer_id="01637680";
    //代征主体
    private static final String broker_id="yiyun73";

    private static final String baseURL="https://api-jiesuan.yunzhanghu.com/";


    /**
     *  云结算上报方法
     * @param orderNo 订单号
     * @param desKey des加密码，数据库中存为公钥
     * @param appkey appkey ，数据库中存为私钥
     */
    public static void yunJieSuanReport(String orderNo,Map<String,Object> data,String desKey,String appkey) throws Exception {
        String reportUrl=baseURL+"api/payment/v1/report-realtime";


        //创建实体类，存入订单上报的必要信息
        YunjiesuanReportBean reportBean=new YunjiesuanReportBean();
        reportBean.setOrder_id(data.get("order_id").toString());
        reportBean.setBroker_id(broker_id);
        reportBean.setDealer_id(dealer_id);
        reportBean.setCard_no(data.get("card_no").toString());
        reportBean.setFinished_time(data.get("finished_time").toString());
        reportBean.setId_card(data.get("id_card").toString());
        reportBean.setReal_name(data.get("real_name").toString());
        reportBean.setPay(data.get("pay").toString());
        reportBean.setBank_bill(data.get("ref").toString());
        String jsonStr= JSONObject.toJSONString(reportBean);
        byte[] enc = YunJieSuanEncrypt.TripleDesEncrypt(jsonStr.getBytes(StandardCharsets.UTF_8), desKey.getBytes(StandardCharsets.UTF_8));
        byte[] enc64 = Base64.encodeBase64(enc);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response=null;
        Map<String,Object> resultMap=null;
        try {

            // 格式
            //随机数
            String param = "data=" + new String(enc64);
            param += "&mess=" + StringUtil.getDateString(6);
            //得到精确到秒时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            timestamp = timestamp.substring(0, timestamp.length() - 3);
            //拼接
            param += "&timestamp=" + timestamp;
            //拼接签名
            String signmessage = param;
            param += "&sign=";
            signmessage += "&key=" + appkey;
            //生成签名
            String sign = sha256HMAC(signmessage,appkey);
            param += sign;
            param += "&sign_type=sha256";
            System.out.println("传递参数：" + param);
            // 将参数输出到连接
            String body = null;
            HttpEntity entity1 = null;
            List<NameValuePair> list = new LinkedList<>();
            BasicNameValuePair param1 = new BasicNameValuePair("data", new String(enc64));
            BasicNameValuePair param2 = new BasicNameValuePair("mess", orderNo);
            BasicNameValuePair param3 = new BasicNameValuePair("timestamp", timestamp);
            BasicNameValuePair param4 = new BasicNameValuePair("sign", sign);
            BasicNameValuePair param5 = new BasicNameValuePair("sign_type", "sha256");
            list.add(param1);
            list.add(param2);
            list.add(param3);
            list.add(param4);
            list.add(param5);


            HttpPost post = new HttpPost(reportUrl);
            //StringEntity entity = new StringEntity(param, "UTF-8");

            UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
            post.setEntity(entityParam);
            post.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");
            post.addHeader("dealer-id", dealer_id);
            post.addHeader("request-id", String.valueOf(System.currentTimeMillis()));
            //logger.info("post:" + post);


            response = httpClient.execute(post);
          /*  response.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            response.setHeader("Content-Type", "application/x-www-form-urlencoded");
            response.setHeader("dealer_id", dealer_id);
            response.setHeader("request_id", orderNo);*/
            //response.setEntity(entityParam);

            entity1 = response.getEntity();
            body = EntityUtils.toString(entity1, "UTF-8");


            if (body != null) {
                Gson gson = new Gson();
                System.out.println(body);
                resultMap = gson.fromJson(body, Map.class);
                String code=resultMap.get("code").toString();
                if(!"0000".equals(code)){
                    System.out.println("---订单号为:--"+orderNo+"-上报失败，失败原因：---"+resultMap.get("message")+"------");
                }else {
                    System.out.println("----订单号为:--"+orderNo+"-上报成功------");
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
